﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using ExtendedEditor.Painter;

namespace ExtendedEditor
{
	/// <summary>
	/// Interaction logic for UserControl1.xaml
	/// </summary>
	public partial class RichTextBoxEx : RichTextBox
	{
		public RichTextBoxEx()
		{
			InitializeComponent();
			index = new ParagraphMetadataCollection();
		}

		private void RichTextBox_Loaded(object sender, RoutedEventArgs e)
		{
			painter = new TextBoxPainter();
			painter.Owner = this;
		}

		private void RichTextBox_Unloaded(object sender, RoutedEventArgs e)
		{

		}

		protected override void OnTextChanged(TextChangedEventArgs e)
		{
			if (this.Document == null) return;
			List<Paragraph> parList = new List<Paragraph>();
			foreach (var item in e.Changes)
			{
			    TextPointer start = this.Document.ContentStart.GetPositionAtOffset(item.Offset);
			    TextPointer end = this.Document.ContentStart.GetPositionAtOffset(item.Offset + item.AddedLength);
			    parList.AddRange(this.Document.GetParagraphRange(start, end));
			}

			//Enumerate all editable blocks
			for (int i = 0; i < parList.Count; i++)
				index.HandleParagraph(parList[i]);

			base.OnTextChanged(e);
		}

		TextBoxPainter painter;
		ParagraphMetadataCollection index;
	}
}
